package lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Non-reentrant biased read-write lock
 * 
 * @author yinzichen
 * 
 */
public class ReadBiasLock implements ReadWriteLock {

	private int readCount;
	private Lock mutex;
	private Condition condition;
	private int pv;

	public ReadBiasLock() {
		readCount = 0;
		pv = 0;
		mutex = new ReentrantLock();
		condition = mutex.newCondition();
	}

	public void readLock() throws InterruptedException {
		synchronized (this) {
			if (readCount == 0) {
				writeLock();
			}
			readCount++;
		}
	}

	public void realseReadLock() {
		synchronized (this) {
			readCount--;
			if (readCount == 0) {
				realseWriteLock();
			}
		}
	}

	public void writeLock() throws InterruptedException {
		mutex.lock();
		try {
			while (pv != 0) {
				condition.await();
			}
			pv = 1;
		} catch (InterruptedException e) {
			throw e;
		} finally {
			mutex.unlock();
		}
	}

	public void realseWriteLock() {
		mutex.lock();
		pv = 0;
		condition.signal();
		mutex.unlock();
	}

}
